package com.feng.chat.interceptor;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.feng.chat.aspect.RequestWrapper;
import com.feng.chat.dto.Result;
import com.feng.chat.entity.Contact;
import com.feng.chat.entity.GroupChat;
import com.feng.chat.entity.GroupMember;
import com.feng.chat.mapper.ContactMapper;
import com.feng.chat.mapper.GroupMapper;
import com.feng.chat.mapper.GroupMemberMapper;
import com.feng.chat.utils.GetUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

/**
 * 消息权限拦截器
 */
@Slf4j
@Component
public class MessageInterceptor implements HandlerInterceptor {
    @Autowired
    private ContactMapper contactMapper;

    @Autowired
    private GroupMapper groupMapper;

    @Autowired
    private GroupMemberMapper groupMemberMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setContentType("application/json;charset=UTF-8");

        /*CustomHttpServletRequestWrapper customHttpServletRequestWrapper = new CustomHttpServletRequestWrapper(request);
        String body = customHttpServletRequestWrapper.getBody();*/

        RequestWrapper requestWrapper = new RequestWrapper(request);
        String body = requestWrapper.getBody();


        log.info("body数据======"+body);

        Map map = JSON.parseObject(body, Map.class);

        int talk_type = (int) map.get("talk_type");
        int receiver_id = (int) map.get("receiver_id");
        Integer userId = GetUserUtil.getUserId(request);
        if (talk_type == 1) { //好友消息
            QueryWrapper<Contact> contactQueryWrapper = new QueryWrapper<>();
            contactQueryWrapper.in("user_id", userId, receiver_id).in("friend_id", receiver_id, userId).eq("status", 2);
            List<Contact> contacts = contactMapper.selectList(contactQueryWrapper);
            if (contacts.size() == 2) {
                log.info("可以发送消息给");
                return true;
            } else {
                PrintWriter out = response.getWriter();
                out.print(JSON.toJSONString(Result.fail("你与对方还不是好友哦！")));
                return false;
            }
        } else if (talk_type == 2) { //群消息
            GroupChat groupChat = groupMapper.selectById(receiver_id);
            if (groupChat.getIsDismiss() == 0) { //群聊是否解散
                QueryWrapper<GroupMember> groupMemberQueryWrapper = new QueryWrapper<>();
                groupMemberQueryWrapper.eq("group_id", receiver_id).eq("user_id", userId).eq("is_quit", 0);
                GroupMember groupMember = groupMemberMapper.selectOne(groupMemberQueryWrapper);
                if (groupMember != null) { //是否是该群群成员
                    log.info("可以发送群消息给");
                    if (groupChat.getIsMute()==0){ //是否开启全员禁言

                        if (groupMember.getIsMute()==0){ //是否被禁言
                            return true;
                        }else{
                            PrintWriter out = response.getWriter();
                            out.print(JSON.toJSONString(Result.fail("您已被群主或管理员禁言！")));
                            out.close();
                            return false;
                        }

                    }else {
                        if (groupMember.getLeader()==1||groupMember.getLeader()==2){ //是否是群主或管理员
                            return true;
                        }
                        PrintWriter out = response.getWriter();
                        out.print(JSON.toJSONString(Result.fail("群主或管理员已开启全员禁言！")));
                        out.close();
                        return false;
                    }

                } else {
                    PrintWriter out = response.getWriter();
                    out.print(JSON.toJSONString(Result.fail("你不是该群群成员！")));
                    out.close();
                    return false;
                }
            } else if (groupChat.getIsDismiss() == 1) {
                PrintWriter out = response.getWriter();
                out.print(JSON.toJSONString(Result.fail("该群聊已解散！")));
                out.close();
                return false;
            }
        }
        PrintWriter out = response.getWriter();
        out.print(JSON.toJSONString(Result.fail("消息发送失败！")));
        out.close();
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
